import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import { useAppDispatch, useAppSelector } from '@/store';
import { clearResultsAction, getResultsAction } from '@/store/action/search';
import { Toast, InfiniteScroll } from 'antd-mobile';
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';

export default function SearchResult() {
  const location = useLocation();
  const params = new URLSearchParams(location.search);
  const dispatch = useAppDispatch();
  const q = params.get('q') as string;

  const { resultData } = useAppSelector((state) => state.search);

  useEffect(() => {
    if (!q) {
      Toast.show({ content: '查询参数不能为空' });
      return;
    }

    dispatch(getResultsAction(q));

    return () => {
      dispatch(clearResultsAction());
    };
  }, [q, dispatch]);

  const loadMore = async () => {
    console.log('我被触发了  ----->  ');
    await dispatch(getResultsAction(q, resultData.page + 1));
  };

  return (
    <div className={styles.root}>
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {resultData.results?.map((item) => {
          return <ArticleItem key={item.art_id} data={item} />;
        })}
      </div>
      {resultData.results?.length && (
        <InfiniteScroll
          loadMore={loadMore}
          hasMore={resultData.results.length < resultData.total_count}
        />
      )}
    </div>
  );
}
